<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  

  
    
    
    <link href="https://fonts.loli.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">




  <meta name="keywords" content="word embeddings," />










<meta name="description" content="中文预训练资料下载   Chinese-Word-Vectors  Tencent AI Lab Embedding Corpus for Chinese Words and Phrases">
<meta name="keywords" content="word embeddings">
<meta property="og:type" content="article">
<meta property="og:title" content="预训练词向量的使用教程">
<meta property="og:url" content="http://codewithzhangyi.com/2019/12/11/using-pre-trained-word-embeddings-in-keras/index.html">
<meta property="og:site_name" content="Zhang Yi">
<meta property="og:description" content="中文预训练资料下载   Chinese-Word-Vectors  Tencent AI Lab Embedding Corpus for Chinese Words and Phrases">
<meta property="og:locale" content="en">
<meta property="og:image" content="https://github.com/YZHANG1270/YZHANG1270.github.io/blob/master/img/word_embedding/002.png?raw=true">
<meta property="og:image" content="https://github.com/YZHANG1270/YZHANG1270.github.io/blob/master/img/word_embedding/001.png?raw=true">
<meta property="og:updated_time" content="2019-12-12T14:59:14.764Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="预训练词向量的使用教程">
<meta name="twitter:description" content="中文预训练资料下载   Chinese-Word-Vectors  Tencent AI Lab Embedding Corpus for Chinese Words and Phrases">
<meta name="twitter:image" content="https://github.com/YZHANG1270/YZHANG1270.github.io/blob/master/img/word_embedding/002.png?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codewithzhangyi.com/2019/12/11/using-pre-trained-word-embeddings-in-keras/"/>






<script data-ad-client="ca-pub-2691877571661707" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  <title>预训练词向量的使用教程 | Zhang Yi</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhang Yi</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle" style="color:#fff">
    <button>MENU</button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-projects">
          <a href="/projects/" rel="section">
            
            Projects
          </a>
        </li>
      
        
        <li class="menu-item menu-item-blog">
          <a href="/blog/" rel="section">
            
            Blog
          </a>
        </li>
      
        
        <li class="menu-item menu-item-activity">
          <a href="/activity/" rel="section">
            
            Activity
          </a>
        </li>
      
        
        <li class="menu-item menu-item-list-100">
          <a href="/list-100/" rel="section">
            
            List 100
          </a>
        </li>
      
        
        <li class="menu-item menu-item-friends">
          <a href="/friends/" rel="section">
            
            Friends
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://codewithzhangyi.com/2019/12/11/using-pre-trained-word-embeddings-in-keras/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ZhangYi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhang Yi">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">预训练词向量的使用教程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-12-11T17:58:21+08:00">
                2019-12-11
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/12/11/using-pre-trained-word-embeddings-in-keras/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2019/12/11/using-pre-trained-word-embeddings-in-keras/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>visitors
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>中文预训练资料下载</strong> </p>
<ul>
<li><a href="https://github.com/Embedding/Chinese-Word-Vectors" target="_blank" rel="noopener">Chinese-Word-Vectors</a> </li>
<li><a href="https://ai.tencent.com/ailab/nlp/embedding.html" target="_blank" rel="noopener">Tencent AI Lab Embedding Corpus for Chinese Words and Phrases</a> </li>
</ul>
<a id="more"></a>
<p>按照词向量不同的维度，可大可小，会有多个版本的预训练词向量，可以根据自己需求进行选择：<br><img src="https://github.com/YZHANG1270/YZHANG1270.github.io/blob/master/img/word_embedding/002.png?raw=true" alt=""></p>
<p>预训练词向量文件，一般比较大很难打开，大部分文件的格式由3个部分组成，以glove举例：</p>
<ol>
<li>第一行有2个数字，左边的表示字典有多少个词，右边的表示词向量的维度</li>
<li>每行的第一个元素是词本身</li>
<li>每行的其它元素是词向量<br><img src="https://github.com/YZHANG1270/YZHANG1270.github.io/blob/master/img/word_embedding/001.png?raw=true" alt=""> </li>
</ol>
<h2 id="预训练词向量的使用步骤"><a href="#预训练词向量的使用步骤" class="headerlink" title="预训练词向量的使用步骤"></a>预训练词向量的使用步骤</h2><ol>
<li>将所有语料转化为词索引序列（word_index）。所谓词索引就是为每一个词一次分配一个整数ID。</li>
<li>生成一个词向量矩阵（embedding_matrix）。第 i 列表示词索引为 i 的词的词向量。</li>
<li>将词向量矩阵载入Keras Embedding层，设置该层的权重不可再训练(也就是说在之后的网络训练过程中，词向量不再改变)。</li>
</ol>
<h3 id="数据预处理"><a href="#数据预处理" class="headerlink" title="数据预处理"></a>数据预处理</h3><p>我们可以将语料样本转化为神经网络训练所用的tensor。所用到的Keras库是keras.preprocessing.text.Tokenizer和keras.preprocessing.sequence.pad_sequences。代码如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">from keras.preprocessing.text import Tokenizer</span><br><span class="line">from keras.preprocessing.sequence import pad_sequences</span><br><span class="line"></span><br><span class="line"># 生成语料词索引序列</span><br><span class="line">tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)</span><br><span class="line">tokenizer.fit_on_texts(texts)</span><br><span class="line">sequences = tokenizer.texts_to_sequences(texts)</span><br><span class="line"></span><br><span class="line">word_index = tokenizer.word_index</span><br><span class="line">print(&apos;Found %s unique tokens.&apos; % len(word_index))</span><br><span class="line"></span><br><span class="line">data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)</span><br><span class="line"></span><br><span class="line"># 标签格式转换</span><br><span class="line">labels = to_categorical(np.asarray(labels))</span><br><span class="line">print(&apos;Shape of data tensor:&apos;, data.shape)</span><br><span class="line">print(&apos;Shape of label tensor:&apos;, labels.shape)</span><br><span class="line"></span><br><span class="line"># 切分成测试集和验证集</span><br><span class="line">indices = np.arange(data.shape[0])</span><br><span class="line">np.random.shuffle(indices)</span><br><span class="line">data = data[indices]</span><br><span class="line">labels = labels[indices]</span><br><span class="line">nb_validation_samples = int(VALIDATION_SPLIT * data.shape[0])</span><br><span class="line"></span><br><span class="line">x_train = data[:-nb_validation_samples]</span><br><span class="line">y_train = labels[:-nb_validation_samples]</span><br><span class="line">x_val = data[-nb_validation_samples:]</span><br><span class="line">y_val = labels[-nb_validation_samples:]</span><br></pre></td></tr></table></figure>
<h3 id="Embedding-layer-设置"><a href="#Embedding-layer-设置" class="headerlink" title="Embedding layer 设置"></a>Embedding layer 设置</h3><p>接下来，我们从词向量预训练文件中解析出每个词和它所对应的词向量，并用字典（embedding_index）的方式存储。下面主要生成embedding_index：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">embeddings_index = &#123;&#125;</span><br><span class="line">f = open(os.path.join(pretrained_wv_dir, &apos;Tencent_AILab_ChineseEmbedding.txt&apos;))</span><br><span class="line">for line in f:</span><br><span class="line">    values = line.split()</span><br><span class="line">    </span><br><span class="line">    # 因为每行的第一个元素是词，后面的才是词向量，因此将values[0]与values[1:]分开存放</span><br><span class="line">    word = values[0]</span><br><span class="line">    coefs = np.asarray(values[1:], dtype=&apos;float32&apos;)</span><br><span class="line">    </span><br><span class="line">    embeddings_index[word] = coefs</span><br><span class="line">f.close()</span><br><span class="line"></span><br><span class="line">print(&apos;Found %s word vectors.&apos; % len(embeddings_index))</span><br></pre></td></tr></table></figure>
<p>此时，我们可以根据得到的embedding_index生成上文所定义的词向量矩阵embedding_matrix：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"># embedding_matrix的维度 =（语料单词的数量，预训练词向量的维度）</span><br><span class="line">embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))</span><br><span class="line"></span><br><span class="line">for word, i in word_index.items():</span><br><span class="line">	# 根据语料生成的word_index来从embedding_index一条条获取单词对应的向量</span><br><span class="line">    embedding_vector = embeddings_index.get(word)</span><br><span class="line">    if embedding_vector is not None:</span><br><span class="line">        # words found in embedding index will be pretrained vectors.</span><br><span class="line">        embedding_matrix[i+1] = embedding_vector   # i+1 是为了处理OOV，使得预测时未见过的词的位置为0。当然如果不使用这种OOV的处理方式的话，这里的embedding_matrix[i+1]应该变成embedding_matrix[i]，下同理。</span><br><span class="line">        else:</span><br><span class="line">        # words not found in embedding index will be random vectors with certain mean&amp;std.如果单词未能在预训练词表中找到，可以自己生成一串向量。</span><br><span class="line">        embedding_matrix[i+1] = np.random.normal(0.053, 0.3146, (1, embed_size))[0] # 0.053, 0.3146 根据统计，可以改变数值</span><br></pre></td></tr></table></figure>
<p>现在我们将这个词向量举证加载到Embedding 层中，注意，我们设置trainable=False使得这个编码层不可再训练。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">from keras.layers import Embedding</span><br><span class="line"></span><br><span class="line">embedding_layer = Embedding(len(word_index) + 1,</span><br><span class="line">                            EMBEDDING_DIM,</span><br><span class="line">                            weights=[embedding_matrix],</span><br><span class="line">                            input_length=MAX_SEQUENCE_LENGTH,</span><br><span class="line">                            trainable=False)</span><br></pre></td></tr></table></figure>
<p>一个Embedding层的输入应该是一系列的整数序列，比如一个2D的输入，它的shape值为(samples,indices)，也就是一个samples行，indices列的矩阵。</p>
<p>下面的是以函数形式写入dictionary模块的demo，跟上面的差不多，仅作参考：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">from gensim.models import KeyedVectors</span><br><span class="line"></span><br><span class="line">def gen_embeddings_index(self, pretrained_wv_path):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    create a weight matrix for words in training docs</span><br><span class="line">    将预训练词向量文本变成字典形式：&#123;word:vector&#125;</span><br><span class="line">    :param pretrained_wv_path: &apos;Tencent_AILab_ChineseEmbedding.txt&apos;  # 预训练的词向量文件</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    # 使用gensim导入预训练词向量文件，不用管第一行的数值处理</span><br><span class="line">    wv_from_text = KeyedVectors.load_word2vec_format(pretrained_wv_path, binary=False)</span><br><span class="line">    embeddings_index = &#123;&#125;</span><br><span class="line">    for word in wv_from_text.vocab:</span><br><span class="line">        embeddings_index[word] = wv_from_text.word_vec(word)</span><br><span class="line">    logging.info(&apos;Loaded &#123;&#125; word vectors.&apos;.format(len(embeddings_index)))</span><br><span class="line"></span><br><span class="line">    return embeddings_index</span><br><span class="line"></span><br><span class="line">def gen_embedding_matrix(self, word_index, embeddings_index, embed_size):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    从庞大的预训练的词向量中，选出训练集中出现的单词的词向量，形成小型的预训练词向量</span><br><span class="line">    :param word_index: local dictionary</span><br><span class="line">    :param embeddings_index: pretrained word vectors</span><br><span class="line">    :param embed_size: 预训练的词向量的维度</span><br><span class="line">    :return:</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">	embedding_matrix = np.zeros((len(word_index) + 1, embed_size))</span><br><span class="line">    for word, i in word_index.items():</span><br><span class="line">        embedding_vector = embeddings_index.get(word)</span><br><span class="line">        if embedding_vector is not None:</span><br><span class="line">            # words found in embedding index will be pretrained vectors.</span><br><span class="line">            embedding_matrix[i+1] = embedding_vector   # i+1 是为了处理OOV，使得预测时未见过的词为0</span><br><span class="line">        else:</span><br><span class="line">            # words not found in embedding index will be random vectors with certain mean&amp;std.</span><br><span class="line">            embedding_matrix[i+1] = np.random.normal(0.053, 0.3146, (1, embed_size))[0] # 0.053, 0.3146 根据统计</span><br><span class="line"></span><br><span class="line">    # save embedding matrix</span><br><span class="line">    embed_df = pd.DataFrame(embedding_matrix)</span><br><span class="line">    embed_df.to_csv(self.path_embedding_matrix, header=None, sep=&apos; &apos;)</span><br><span class="line"></span><br><span class="line">    return embedding_matrix</span><br></pre></td></tr></table></figure>
<p><strong>写在最后</strong> </p>
<p>之前在做QA任务的优化时，尝试使用预训练的词向量，那时候还没直接用Bert。先说结果：效果提升不大，甚至说没啥提升。</p>
<p>主要原因：某垂直领域的词向量，太接近了，起不到分开词意的作用。词向量可能在非常泛的语义区分中有作用，比如在聊天的时候，谈的天南地北，能分清钢琴和大米是两回事，但是可能分不清钢琴和吉他，甚至两个向量表达十分地接近。</p>
<p>后面接触Bert之后，就没有深入再做词向量预训练的工作了，只能说Bert使人懒惰😂，接下来会写几篇Bert实战相关文章，敬请期待~</p>
<p>参考：<br><a href="https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html" target="_blank" rel="noopener">Using pre-trained word embeddings in a Keras model</a> </p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>打赏2块钱，帮我买杯咖啡，继续创作，谢谢大家！☕~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="ZhangYi WeChat Pay"/>
        <p>WeChat Pay</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/word-embeddings/" rel="tag"># word embeddings</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/11/06/add-local-img/" rel="next" title="如何在Hexo中添加本地图片">
                <i class="fa fa-chevron-left"></i> 如何在Hexo中添加本地图片
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/12/12/way-to-money/" rel="prev" title="程序媛如何利用业余时间月入过万">
                程序媛如何利用业余时间月入过万 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-2691877571661707"
     data-ad-slot="1301633292"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="ZhangYi" />
            
              <p class="site-author-name" itemprop="name">ZhangYi</p>
              <p class="site-description motion-element" itemprop="description">花时间做那些别人看不见的事~！</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/YZHANG1270" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:YZHANG1270@gmail.com" target="_blank" title="邮箱">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/p/1005053340707810?is_all=1" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#预训练词向量的使用步骤"><span class="nav-text">预训练词向量的使用步骤</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据预处理"><span class="nav-text">数据预处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Embedding-layer-设置"><span class="nav-text">Embedding layer 设置</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ZhangYi</span>

  
</div>








  <div class="footer-custom">All content under <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/">CC BY-NC-ND 4.0</a></div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      visitors
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>


  


  
  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://codewithzhangyi.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://codewithzhangyi.com/2019/12/11/using-pre-trained-word-embeddings-in-keras/';
          this.page.identifier = '2019/12/11/using-pre-trained-word-embeddings-in-keras/';
          this.page.title = '预训练词向量的使用教程';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://codewithzhangyi.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  


  

  

</body>
</html>
